from django.db.models.query import InstanceCheckMeta
from rest_framework import response, viewsets, status
from .models import ShippingContainer, Task
from .serializers import ShippingContainerSerializer, TaskSerializer
from celery_client.tasks import on_task_submitted


class ShippingContainerViewset(viewsets.ModelViewSet):
    query = ShippingContainer.objects.all()
    serializer_class = ShippingContainerSerializer  # XU LIE HUA /FAN HU LIE HUA
# Create your views here.


class TaskViewSet(viewsets.ModelViewSet):

    queryset = Task.objects.all()

    serializer_class = TaskSerializer

    def partial_update(self, request, *args, **kwargs):
        """
        处理 PATCH /api/tasks/<id>/ 请求
        根据请求体json的内容，做如下操作:

        1 如果请求体中存在 "submit: True",则立刻提交计算任务
        2 否则，按需更新任务本身，比如任务名，任务数据 ...

        """
        # 获取flag:是否立刻提交任务
        submit_now = request.data.pop('submit', False)

        print(request.data)
        print('-' * 30)
        # 处理操作 - 一般的任务更新
        super().partial_update(request, *args, **kwargs)
        instance = self.get_object()

        # 继续处理
        if submit_now:
            # 向负责任务状态控制的Celery worker提交信息
            # "on_task_submitted" 定义在本地代码中，所以可以直接import
            # 并调用定义在该函数上的.apply来提交celery task
            on_task_submitted.apply([{
                'tenant_id': request.user.tenant.id,
                'task_id': instance.id
            }])

            instance = self.get_object()

        return response.Response(
            self.get_serializer(instance).data,
            status=status.HTTP_200_OK
        )
